package com.onlinevideo.servlet;

import cn.hutool.json.JSONUtil;
import com.onlinevideo.data.ResultBean;
import com.onlinevideo.entity.Message;
import com.onlinevideo.entity.User;
import com.onlinevideo.service.MessageService;
import com.onlinevideo.service.impl.MessageServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class MessageServlet extends BaseServlet {
    PrintWriter writer;
    MessageService messageService = new MessageServiceImpl();

    protected void getMessage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        writer = resp.getWriter();
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        String haveReadStr = req.getParameter("haveRead");
        if (haveReadStr == null) {
            haveReadStr = "0";
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Integer haveRead1 = Integer.valueOf(haveReadStr);
        List<Message> messages = messageService.queryByUserId(user.getId(), haveRead1);
        for (Message message : messages) {
            String time = message.getTime();
            Date date = new Date();
            date.setTime(Long.parseLong(time));
            time = simpleDateFormat.format(date);
            message.setTime(time);
        }
        writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("获取已读消息", messages)));
    }


    protected void readMessage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        writer = resp.getWriter();
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        Long id = Long.valueOf(req.getParameter("id"));
        Message message = messageService.queryById(id);
        message.setHasRead(1);
        int update = messageService.update(message);
        if (update > 0) {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("已读", message)));
        } else {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("读取失败")));
        }
    }

    protected void clearMessage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        writer = resp.getWriter();
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        int i = messageService.deleteByUserRead(user.getId());
        if (i > 0) {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("消息已清空")));
        } else {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("清除消息失败")));
        }
    }
}
